<template>
	<view class="p-uploader-bd" :class="'upload_box_'+size+' upload_box_'+mode">
		<view class="p-uploader-files">
			<block v-for="(item, index) in uploaded_list" :key="index">
				<view class="p-uploader-file p-uploader-file-status" @click="previewImage(index)">
					<!-- step1.这里修改服务器返回字段 ！！！ -->
					<image class="p-uploader-img"  :src="item.path ? item.path : item.url"  mode="widthFix"/>
					<view class="p-img-removeicon right" @click.stop="removeImage(index)" v-show="upimg_move">×
					</view>
					<!-- <view class="p-loader-filecontent" v-if="item.upload_percent < 99">{{ item.upload_percent }}%</view> -->
				</view>
			</block>
			<view v-show="upload_len < upload_count" hover-class="p-uploader-hover" :class="'p-uploader-inputbox '+ mode"
				@click="chooseImage">
				<view>
					<image v-if="defaultImage" :src="defaultImage" mode='heightFix'></image>
					<image v-else-if="mode=='image' || mode=='camera'" src="/static/input-upload/image.png" mode="heightFix" ></image>
					<image v-else-if="mode=='idcard_front'" src="/static/input-upload/idcard_front.png" mode="heightFix" ></image>
					<image v-else-if="mode=='idcard_back'" src="/static/input-upload/idcard_back.png" mode="heightFix" ></image>
					<image v-else-if="mode=='idcard_holding'" src="/static/input-upload/idcard_holding.png" mode="heightFix" ></image>
					<image v-else-if="mode=='truck-front'" src="/static/input-upload/truck-front.png" mode="heightFix" ></image>
					<image v-else-if="mode=='truck-side'" src="/static/input-upload/truck-side.png" mode="heightFix" ></image>
					<image v-else-if="mode=='card'" src="/static/input-upload/upload-card.png" mode="heightFix" ></image>
					<image v-else-if="mode=='avatar'" src="/static/input-upload/avatar.png" mode="heightFix" ></image>
					<text v-else style="width:100%;display: inline-block;margin-top:5px">上传图片</text>
					<text v-if="title">{{title}}</text>
				</view>
	
			</view>
	
		</view>
	</view>

</template>

<script>
	import ImageService from '@/service/image.js';
	import permission from '../../libs/permission/index.js';

	export default {
		props: {
			value: {
				type: [String, Number,Array],
				default: ''
			}, 
			defaultImage: {
				type: String,
				default: () => {
					return ''
				}
			},
			returnType: {
				type: String,
				default: () => {
					return 'string'
				}
			},
			
			title: {
				type: String,
				default: () => {
					return ''
				}
			},
			size: {
				type: [String],
				default: 'normal'//normal、small
			}, 
			mode: {
				type: String,
				default: () => {
					return 'image'//avatar
				}
			},
			url: {
				type: String,
				default: 'https://upload.houjiji.com/api/upload',
			},
			// 上传数量
			upload_count: {
				type: [Number, String],
				default: 1
			},
			// 是否自动上传? 可以先用变量为false然后再改为true即为手动上传
			upload_auto: {
				type: Boolean,
				default: true
			},
			// 是否显示删除
			upimg_move: {
				type: Boolean,
				default: true
			},
			// 服务器返回预览(看服务器卡顿情况设定)
			upimg_delaytime: {
				type: [Number, String],
				default: 300
			},
	
		},
		data() {
			return {
				images: this.value,
				upload_len: 0,
				upload_cache: [],
				uploaded_list: [],//已上传列表
				upload_queue_list: [],
				header: {},
				imageFiles: [],
			}
		},
		async created(options) {
			console.log('created');
			this.upload_queue_list = [];
			this.uploaded_list = [];
			this.upload_len = this.upload_queue_list.length;
			
			this.setUploadedImages(this.images);
			
			ImageService.get_token(token=>{
				if (token){
					this.header={'token':token};
				}
			});
		},
		watch:{
			value: {
				handler(newVal) {
					this.images = newVal || '';
					this.setUploadedImages(this.images);
					
				},
				immediate: true
			},
		},
		methods: {
			setUploadedImages(val){
				let list = val && Array.isArray(val)?val:(val?val.split(','):[]);
				this.upload_queue_list = [];
				this.uploaded_list = [];
				let url,filename;
				for(var i=0;i<list.length;i++){
					url = list[i];
					if (!url){
						continue;
					}
					filename = url.substring(url.lastIndexOf('/')+1,url.lastIndexOf('/')<url.lastIndexOf('?')?url.lastIndexOf('?'):url.length);
					this.upload_queue_list.push( {name:filename,path:url,present:100});
					this.uploaded_list.push({name:filename,url:url});
				}
				this.upload_len = this.upload_queue_list.length;

			},
			upImage(paths, header) {
				let _self = this;

				const promises = paths.map(function(path) {
					return promisify(upload)({
						url: _self.url,
						path: path,
						name: 'image',
						extra: header,
						//_self: _self
					});
				});
				
				//console.log('paths, header', paths, header)
				Promise.all(promises)
					.then(function(data) {
						// uni.hideLoading();
						//console.log('Promise.all uploaded_list', data)
						_self.uploaded_list.push(...data);
						_self.emit();
					})
					.catch(function(res) {
						if (res && res.msg){
							uni.showToast({
								title:res.msg,
								icon:'none'
							})
						}
						
						// uni.hideLoading();
					});
			},
//图片压缩
			imgCompress(tempFilePaths) {

				let _self = this;
				let compressImgs = [];
				let results = [];
				tempFilePaths.forEach((item, index) => {
					//console.log('item', item)
					compressImgs.push(new Promise((resolve, reject) => {
						uni.compressImage({
							src: item,
							quality: 75,    // 仅对jpg有效
							success: res => {
								//console.log('compressImage', res.tempFilePath)
								results.push(res.tempFilePath);
								resolve(res.tempFilePath);
							},
							fail: (err) => {
								reject(err);
							},
							complete: () => {
							}
						})
					}))
				})
				Promise.all(compressImgs) //执行所有需请求的接口
					.then((results) => {
						_self.upload_cache = results;
						_self.upload(_self.upload_auto);						
					})
					.catch((res, object) => {
						_self.upload(_self.upload_auto);
						uni.hideLoading();
					});
			},
			
			async chooseImage() {
				let _self = this;
				let sourceType = ['album', 'camera'];
				if (this.mode=='camera'){
					sourceType = ['camera'];
				}
				permission.request('album').then(res=>{
					uni.chooseImage({ //调chooseImage会判断权限
						count: _self.upload_count - _self.upload_queue_list.length,
						sizeType: [ 'compressed','original'],
						sourceType: sourceType,
						success: function(res) {
							uni.hideLoading();
							uni.showLoading({
								title: '处理中，请稍等',
								mask: true,
								icon: 'loading'
							})

							//console.log('res', res)

							for (let i = 0, len = res.tempFiles.length; i < len; i++) {
								res.tempFiles[i]['upload_percent'] = 0;
								_self.upload_queue_list.push(res.tempFiles[i]);
							}
							//_self.upload_cache = res.tempFilePaths;
							_self.imgCompress(res.tempFilePaths);//_self.upload(_self.upload_auto);

						},
						fail: function(err) {
							//console.log('取消相册', err, err.code)
							if (err.errMsg.indexOf('permission')>=0 ||err.errMsg.indexOf('权限')>=0 ){
								_self.dialog.ask('暂无访问相册权限，是否进行设置？').then(()=>{
									permission.setting('album');
								});
								
							}
						},
						complete(){
							
						}
					});


				}).catch((result,err)=>{
					_self.dialog.ask('暂无访问相册权限，是否进行设置？').then(()=>{
						permission.setting('album');
					});
				});

			},

			async upload(upload_auto) {
				let _self = this;
				upload_auto ? await _self.upImage(_self.upload_cache, _self.header) : console.warn(
					`传输参数:this.$refs.xx.upload(true)才可上传,默认false`);
			},
			
			previewImage(idx) {
				let _self = this;
				let preview = [];
				for (let i = 0, len = _self.uploaded_list.length; i < len; i++) {
					// step3.这里修改服务器返回字段 ！！！
					preview.push(_self.uploaded_list[i].url);
				}
				uni.previewImage({
					current: idx,
					urls: preview
				});
			},
			removeImage(idx) {
				uni.showLoading({
					title: '正理中，请稍等',
					mask: true,
					icon: 'loading'
				})				
				let _self = this;
				_self.upload_queue_list.splice(idx, 1);
				_self.uploaded_list.splice(idx, 1);
				_self.upload_len = _self.upload_queue_list.length;
				setTimeout(function() {
					_self.$emit('change', _self.uploaded_list);
					uni.hideLoading();
					clearTimeout();
				}, 1000);
				//console.log('upload_queue_list', _self.upload_queue_list)
				//console.log('_self.uploaded_list', _self.uploaded_list)
			},
			emit() {
				
				this.upload_len = this.upload_queue_list.length;
				
				//console.log('start_emit',this.uploaded_list)
				this.$emit('change', this.uploaded_list);
				
				this.images = '';
				let newArr = [];
				for (let i in this.uploaded_list) {
					newArr.push(this.uploaded_list[i].url);
				}
				this.images = newArr.join(',');
				this.$emit('input', this.returnType=='array'?newArr:this.images);
				
				//console.log('end_emit')
			},
			setImage(index,path) {
				let that = this;
					this.upload_cache = [path];
					//console.log('this.upload_cache',this.upload_cache);
					this.upload(_self.upload_auto);
			},
			
			async takeCamera(){
				//#ifndef H5
				uni.navigateTo({
				  url: './id_card?type='+index
				})
				//#endif
			},
			
			
		}
	}
	const promisify = api => {
		return function(options, ...params) {
			return new Promise(function(resolve, reject) {
				api(
					Object.assign({}, options, {
						success: resolve,
						fail: reject
					}),
					...params
				);
			});
		};
	};
	
	const upload = function(options) {
		//console.log('options', options)
	
		let url = options.url,
			_self = options._self,
			path = options.path,
			name = options.name,
			// data = options.data,
			header = options.header,
			extra = options.extra,
			success = options.success,
			progress = options.progress,
			fail = options.fail;
	
		uni.showLoading({
			title: '上传中～请稍等',
			mask: true,
			icon: 'loading'
		})
	
		const uploadTask = uni.uploadFile({
			url: url,
			filePath: path,
			name: name,
			formData: {
				'user': 'test'
			},
			header: extra,
			success: function(res) {
	
				var data = res.data;
				try {
					//Tip : 切记->主要修改这里图片的返回值为真实返回路径!!! 详情见示例
					data = JSON.parse(res.data);
				} catch (e) {
					throw (e, data);
				}
				// 根据自己的返回数据做相应判断,服务器返回200即代表成功请求
				
				if (data.msg == 'success') {
					if (success) {
						success(data.data);
					}
				} else {
					if (fail) {
						fail(data);
					}
				}
				uni.hideLoading();
			},
			fail: function(res) {
				//console.log(res);
				if (fail) {
					fail(res);
				}
				uni.hideLoading();
			}
		});
		uploadTask.onProgressUpdate(async function(res) {
			
			//console.log('res', res)
			if (_self){
				for (let i = 0, len = _self.upload_queue_list.length; i < len; i++) {
					_self.upload_queue_list[i]['upload_percent'] = await res.progress;
				}
				_self.upload_len = _self.upload_queue_list.length;
	
				//console.log('onProgressUpdate', _self.upload_queue_list, _self.upload_len)
			}
		});
	};
</script>

<style lang="scss">
	@font-face {
		font-family: 'iconfont';
		src: url('//at.alicdn.com/iconfont.eot?t=1574391686418');
		/* IE9 */
		src: url('//at.alicdn.com/iconfont.eot?t=1574391686418#iefix') format('embedded-opentype'),
			/* IE6-IE8 */
			url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAMkAAsAAAAAB2QAAALYAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCCcAqCYIJEATYCJAMICwYABCAFhG0HPRt3BhEVlCNkH4dxmzUXNsJHc1SNfR9KTkCtiXv/l+QDBQSFRBJdKoEsg60HUgCsOpWVnWxNx3BvVITqkj3fepbtzM/OfDo4D86iFEIiJAeX02+Bh/O84TLmsrEnYBxQoHtgm6xACoxTkN0zFsgEdQynCShpq7cwbsK0eTKROSkgbNu8cbUspRFrkoNMkC9ZGYWjcrJkX/IIR/zPhz/6hIxELmWmzdowfp1RvxdbYWm1VrUMCO54JvDrSNEbkTCv1DJDGvp6S5VUX9SRdSUHfi+u1cBZ7R+PQMgzEyugNcU5J67DO9VfJiCigD042iuNQqXSunGRfvrWV6/mvX49/+3bhW/eLHr4puOFtxMfvO5w9tX8yv7rIbf3Rrl84Mbe66XSzWet46nn/etMuALua5LqNZUqpKdfDKjsv2qef+yambJsTWM2zDtKIQ0pS7msvSTUpn1tNyts2xZmWUyw3LI4bPisSZNyOUc2y4/scfZs3QZ1UcgqUWtkVednsvnVs7NOHzmqglXIBnqU7+/M9Hp3y3L2RLWYA9uhlat61/LGGwVqt9Nvafv/8R2fmg/pu7LesH9ZOYL3/6e3P6Z2O0rbIztra+Dtc1u2RY1vapOocEtDiT0Kd1VUUkIN42joS19Fk1s1BVmKy0OioA2kMp1REdcbcsr6QV5mJJT0MnF9mbQRchZiET29CAT1fSBR1y1I1fdFRdwPcpr6Q179cIaSBaHRjmVdgxFjCSvGFuonmGYcpK1nESRfUC1dRUm+T3ggeeOEOIiywRwHpDHm+FUlzBIkjT1k5DzsuhEmGi02HGjmKQ1DWfaioBn7gzAWQRWGWqD2BIzGaCDRm4nc+y+QsuhUqKaqyviAiGcGB7FA1AKVS4ZWVddyibdSEoxJQCKjHsjIMNTpjMBUPsxCDRbQPTyTVGh1k20lwfyy/un2QYmpTII1I9Vo+1B4XQ2q0QvwvExGfTgA') format('woff2'),
			url('//at.alicdn.com/iconfont.woff?t=1574391686418') format('woff'), url('//at.alicdn.com/iconfont.ttf?t=1574391686418') format('truetype'),
			/* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
			url('//at.alicdn.com/iconfont.svg?t=1574391686418#iconfont') format('svg');
		/* iOS 4.1- */
	}

	@charset "UTF-8";

	.img_text {

		position: absolute;
		left: 95px;
		top: 26px;
	}

	.img_text text {
		font-size: 12px;
		color: #999;
		white-space: nowrap;
		display: inline-block;
	}

	.iconfont {
		font-family: 'iconfont' !important;
		font-size: 16px;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
	}

	.icon-mn_shangchuantupian {
		&:before {
			content: '\e559';
		}

		font-size: 80px;
	}

	.p-uploader-img {
		display: block;
	}

	.p-uploader-input {
		position: absolute;
		z-index: 1;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		opacity: 0;
	}

	.p-uploader-inputbox {
		position: relative;
		margin-bottom: 16rpx;
		box-sizing: border-box;
		background-color: #ededed;
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		justify-content: center;

	}

	.p-uploader-inputbox image {
		width: auto;
		height:162rpx;
	}
	.image {
		width:162rpx;
		height:162rpx;
	}
	.image image {
		width: auto;
		height:80rpx;
	}
	.p-uploader-inputbox text {
		width: 100%;
		display: inline-block;
		font-size: 12px;
	}

	.p-img-removeicon {
		position: absolute;
		color: #fff;
		width: 40upx;
		height: 40upx;
		line-height: 40upx;
		z-index: 2;
		text-align: center;
		background-color: #e54d42;

		&.right {
			top: 0;
			right: 0;
		}
	}

	.p-uploader-file {
		position: relative;
		margin-right: 16rpx;
		margin-bottom: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.p-uploader-file image {
		width:162rpx;
	}
	.p-uploader-file-status:before {
		content: ' ';
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.p-loader-filecontent {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		color: #fff;
		z-index: 9;
	}

	.p-uploader-bd {
		padding: 26rpx;
		margin: 0;
	}

	.p-uploader-files {
		display: flex;
		flex-wrap: wrap;
		position: relative;
	}

	.p-uploader-file:nth-child(3n + 0) {
		margin-right: 0;
	}

	.p-uploader-inputbox>view {
		text-align: center;
	}

	.p-uploader-file-status:after {
		content: ' ';
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.p-uploader-hover {
		box-shadow: 0 0 0 #e5e5e5;
		background: #e5e5e5;
	}
	.upload_box_small{
		padding:5px 5px 5px 10px;
		
		.p-uploader-inputbox{
			border-radius: 5px;
			padding:5px;
		}
		.image,.p-uploader-files image{
			width:60px;
			height:60px;
		}
		.uni-icons{
			margin-top:0;
		}

	}
	.upload_box_mini{
		padding:5px 5px 5px 10px;
		
		.p-uploader-inputbox{
			border-radius: 5px;
			padding:5px;
		}

		.image,.p-uploader-files image{
			width:32px;
			height:32px;
		}
		.uni-icons{
			margin-top:0;
		}
	
	}
	.upload_box_avatar{
		padding:5px;
		.p-uploader-inputbox{
			background:none;
			margin-bottom:0;
		}
		.avatar,.p-uploader-file image{
			width:60px;
			height:60px;
		}
		.p-uploader-inputbox image{
			width:60px;
			height:60px;			
		}
	}
	
</style>

